<template>
  <Modal
      :draggable="!$config.mask"
      :mask="$config.mask"
      :mask-closable="!$config.mask"
      :value="value"
      @on-ok="save"
      @on-visible-change="visibleChange"
      width="1000"
  >
    <p slot="header">
      {{ title }}<span v-if="modalData.update">{{ modalData.data.displayName }}</span>
    </p>
    <Form ref="form" :model="role" :rules="rules" label-postion="top">
      <Tabs v-model="tab">
        <TabPane label="角色详情" name="a">
          <FormItem label="角色名" prop="displayName">
              <Input v-model="role.displayName" :maxlength="64" placeholder=""></Input>
          </FormItem>
          <FormItem label="角色描述" prop="description">
              <Input v-model="role.description" :maxlength="5000" placeholder=""></Input>
          </FormItem>
          <FormItem>
            <Checkbox v-model="role.isDefault">
              新用户默认拥有此角色
            </Checkbox>
          </FormItem>
        </TabPane>
        <TabPane :label="getUserLabel" name="b">
          <div>
            <o-u-user-select ref="userSelect" v-model="selectedUsers"></o-u-user-select>
          </div>
        </TabPane>
        <TabPane :label="getPermissionLabel" name="c">
          <div>
            <Card dis-hover class="pandx">
              <tree-select-common ref="treeSelect" property="name" v-model="selectedNodes" :data="treeData"
                                  :show-checkbox="true" :check-directly="true" :tag-show="false" tag-color="success"
                                  :check-strictly="false" :indeterminate="true"></tree-select-common>
            </Card>
            <div style="margin-top:10px;">
              <Alert type="warning" style="margin-bottom:0;">如果您正在更改自己的权限，则可能需要刷新页面（F5），以便权限更改生效！</Alert>
            </div>
          </div>
        </TabPane>
      </Tabs>
    </Form>
    <div slot="footer">
      <Button icon="md-close" @click="cancel">取消</Button>
      <Button icon="md-checkmark" type="primary" @click="save">确定</Button>
    </div>
  </Modal>
</template>

<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import Role from '@/store/entities/administration/role/role';
import Ajax from '@/lib/ajax';
import TreeSelectCommon from '@/components/select/tree-select-common.vue';
import OUUserSelect from '@/components/select/o-u-user-select.vue';

@Component({
  components: {TreeSelectCommon, OUUserSelect},
})
export default class RoleModal extends AbpBase {
  name: string = 'RoleModal';

  @Prop({type: Boolean, default: false}) value: boolean;
  @Prop({type: Object}) modalData: any;

  tab: string = 'a';
  role: Role = new Role();

  selectedUsers: any[] = [];
  selectedNodes: any[] = [];
  rules = {
    displayName: [
      {
        required: true,
        message: '角色名是必须的',
        trigger: 'blur',
      },
      {
        validator: async (rule, value, callback) => {
          const response = await Ajax.post('/api/services/app/Role/ValidateRole', {
            value: value,
            id: this.modalData.update ? this.modalData.data.id : 0,
          });
          if (response.data.result.status) {
            callback();
          } else {
            callback(new Error(response.data.result.message));
          }
        },
        trigger: 'blur',
      },
    ],
  };

  get title() {
    if (this.modalData.update) {
      return '更新角色：';
    } else {
      return '新建角色';
    }
  }

  get treeData() {
    return this.getTreeData(0, null);
  }

  getUserLabel(h) {
    return h('div', [
      h('span', '角色用户'),
      h('Badge', {
        props: {
          count: this.selectedUsers.length,
          type: 'primary',
        },
        style: {
          marginLeft: '4px',
        },
      }),
    ]);
  }

  getPermissionLabel(h) {
    return h('div', [
      h('span', '角色权限'),
      h('Badge', {
        props: {
          count: this.selectedNodes.length,
          type: 'primary',
        },
        style: {
          marginLeft: '4px',
        },
      }),
    ]);
  }

  getTreeData(level: number, parentName: string) {
    let data: any[] = [];
    const p = this.$store.state.permission.permissions;
    p.forEach((item) => {
      if (item.level === level) {
        if (item.parentName === parentName) {
          let node: any = {};
          node.title = item.displayName;
          node.expand = true;
          node.extra = item;
          node.name = item.name;
          node.children = this.getTreeData(level + 1, item.name);
          data.push(node);
        }
      }
    });
    return data;
  }


  async save() {
    (this.$refs.form as any).validate(async (valid: boolean) => {
      if (valid) {
        console.log('selectedNodes',this.selectedNodes.map((item) => {
          return item.extra.name;
        }));
        await this.$store.dispatch({
          type: 'role/createOrUpdateRole',
          data: {
            role: this.role,
            grantedPermissionNames: this.selectedNodes.map((item) => {
              return item.extra.name;
            }),
            userIds: this.selectedUsers.map((item) => {
              return item.id;
            }),
          },
        });
        if (this.modalData.update) {
          this.$Message.success({
            background: true,
            content: '角色 ' + this.role.displayName + ' 已更新成功',
            duration: this.$config.duration,
          });
        } else {
          this.$Message.success({
            background: true,
            content: '角色 ' + this.role.displayName + ' 已新建成功',
            duration: this.$config.duration,
          });
        }
        this.$emit('save-success');
        this.$emit('input', false);
      }
    });
  }

  cancel() {
    this.$emit('input', false);
  }

  reset() {
    (this.$refs.form as any).resetFields();
    this.selectedNodes = [];
    this.tab = 'a';
    this.role = new Role();

    (this.$refs.userSelect as any).selectedUsers = [];
    (this.$refs.userSelect as any).clickAll();
    ((this.$refs.userSelect as any).$refs.tableSelect as any).filter = '';
    ((this.$refs.userSelect as any).$refs.tableSelect as any).sorting = '';
    ((this.$refs.userSelect as any).$refs.tableSelect as any).currentPage = 1;
  }

  visibleChange(value: boolean) {
    if (!value) {
      this.reset();
      this.$emit('input', value);
    } else {
      if (this.modalData.update) {
        this.role = this.$store.state.role.roleForEdit.role;
        this.selectedNodes = this.$store.state.role.roleForEdit.grantedPermissionNames;
        console.log('selectedNodes1',this.selectedNodes);
        console.log('treeData',this.treeData);
        console.log('granted',this.$store.state.role.roleForEdit.grantedPermissionNames);
        (this.$refs.treeSelect as any).setSelectedNode(this.treeData, this.$store.state.role.roleForEdit.grantedPermissionNames);
        (this.$refs.userSelect as any).selectedUsers = this.$store.state.role.roleForEdit.users;
      } else {
        (this.$refs.treeSelect as any).setSelectedNode(this.treeData, [])
      }
    }
  }

  mounted() {
    const leftCard = (this.$refs.userSelect as any).$el.getElementsByClassName('ivu-col')[0].getElementsByClassName('ivu-card-body')[0];
    leftCard.classList.add('beautiful-bar');
    leftCard.style.height = '500px';
    leftCard.style.overflow = 'auto';
  }
}
</script>

<style lang="less" scoped>
.pandx::v-deep {
  /*定义整个弹出框的高度*/

  .ivu-card-body {
    height: 499px;
    overflow-y: auto;
  }

  .ivu-card-body::-webkit-scrollbar {
    width: 4px;
    background-color: #fff;
  }

  .ivu-card-body::-webkit-scrollbar-thumb {
    border-radius: 2px;
    -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
    background-color: #e8eaec;
  }

  .ivu-card-body::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
    border-radius: 2px;
    background-color: #fff;
  }
}

.ivu-tabs::v-deep {
  .ivu-table-body {

    height: 338px;
    min-height: 338px;
    overflow-y: auto;
  }

  .ivu-table-tip {
    height: 338px;
    min-height: 338px;
    overflow-y: auto;
  }
}
</style>
